
enum TagType {
  YEAR(0), MONTH(1)
  public final int id
  TagType(int v) {
    this.id = v
  }
}

class Tag {

  static constraints = {
    name(maxSize:64,blank:false)
  }

  String name
  int tagType

  static Tag getByNameAndType(String n, TagType tt) {
    if(n == null || tt == null) {
      return null
    }

    return Tag.find(new Tag(name:n, tagType:tt.id))
  }

  static Tag getOrCreateTagForNameAndType(String n, TagType tt) {
    Tag tag = Tag.getByNameAndType(n, tt)

    if(tag == null) {
      println("Could not find, creating")
      tag = new Tag()
      tag.name = n
      tag.tagType = tt.id
      tag.save()
    }

    return tag
  }

  static List<Tag> getYearTags() {
    def tags = Tag.findAllByTagType(TagType.YEAR.id)
    return tags.sort{x -> x.name.toInteger()}
  }

  static List<Tag> getMonthTagsForYear(Tag yearTag) {
    if(yearTag == null) {
      return []
    }

    List<Tag> tags = Tag.executeQuery("select distinct t from Tag as t, MasterTag as mt " +
                             "where t.id = mt.tagId and mt.masterId in " +
                             "(select distinct mt.masterId from MasterTag as mt where mt.tagId = :yearTagId) " +
                             "and t.tagType = :monthTagType " +
                             "order by t.id", [yearTagId:yearTag.id, monthTagType:TagType.MONTH.id])

    return tags.sort{x->x.name.toInteger()} 
  }

  static createAssociations(Master m, Tag... ts) {
    for(t in ts) {
      def mt = new MasterTag()
      mt.masterId = m.id
      mt.tagId = t.id
      mt.save()
    }
  }
}
